package com.lzy.cloud.search.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lzy.cloud.search.client.entity.EsQuery;
import com.lzy.cloud.search.client.service.AggregationsService;
import com.lzy.cloud.search.client.util.EsClient;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 在搜索中添加聚合
 */
@Service
public class AggregationsServiceImpl  implements AggregationsService {

    @Autowired
    private EsClient client;

    @Override
    public void searchAggregations(EsQuery esQuery)   {
        SearchResponse sr = client.getConnection().prepareSearch("twitter")
//                .setQuery(QueryBuilders.matchAllQuery())
                .setQuery(QueryBuilders.matchAllQuery())
                .addAggregation(
                        AggregationBuilders.terms("agg1").field("user")  //
                )
//                .addAggregation(
//                        AggregationBuilders.dateHistogram("agg2")
//                                .field("birth")
//                                .dateHistogramInterval(DateHistogramInterval.YEAR)
//                )
                .get();

        // Get your facet results
        Terms agg1 = sr.getAggregations().get("agg1");
//        Histogram agg2 = sr.getAggregations().get("agg2");

        //打印
        SearchHit[] searchHits = sr.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            System.out.println(JSON.toJSONString(searchHit.getSourceAsString(), SerializerFeature.PrettyFormat));
        }
        System.out.println("" + agg1.getName());
        System.out.println("agg1:" + agg1.getBuckets().toString());

        for (Terms.Bucket bucket :
                agg1.getBuckets()) {
            System.out.println("" + bucket.getDocCount());
        }


        //注意： 可能会报Fielddata is disabled on text fields by default
        //聚合这些操作用单独的数据结构(fielddata)缓存到内存里了，需要单独开启，官方解释在此fielddata
        //https://www.elastic.co/guide/en/elasticsearch/reference/current/fielddata.html
    }

}
